# Create your views here.
from django.shortcuts import render_to_response
from registration.models import  User
from courses.models import Course,Request
from quiz.models import Lecture,Quiz,Answer,Grade
from messagingBoard.models import Message
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django import http
from django import  forms
from STIP.settings import MEDIA_ROOT
# list of mobile User Agents
mobile_uas = [
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
    'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
    'wapr','webc','winw','winw','xda','xda-','iPad'
    ]
 
mobile_ua_hints = [ 'SymbianOS','Windows CE', 'Nokia', 'PSP', 'Opera Mini', 'iPhone', 'iPad', 'Android', 'Opera Mobi', 'webOS' ]
 
 
def mobileBrowser(request):
    ''' Super simple device detection, returns True for mobile devices '''
 
    mobile_browser = False
    ua = request.META['HTTP_USER_AGENT'].lower()[0:4]

    if (ua in mobile_uas):
        mobile_browser = True
    else:
        for hint in mobile_ua_hints:
            if request.META['HTTP_USER_AGENT'].find(hint) > 0:
                mobile_browser = True
 
    return mobile_browser

def getchoice(request,user_id,quiz_id):
    user=request.user
    sub=User.objects.get(pk=user_id)
    quiz=Quiz.objects.get(pk=quiz_id)
    grade=Grade.objects.filter(quiz=quiz, user=sub)
    return render_to_response('quizs/grade.html', context_instance=RequestContext(request,{'course': quiz.lecture.course,'sub' : sub, 'quiz' : quiz,'user' : user, 'grade' : grade}))
def msgdone(request,msg_id):
    user=request.user
    msg=Message.objects.get(pk=msg_id)
    msg.delete()
    url="/messages/list/"+str(msg.lecture.id)
    return HttpResponseRedirect(url);
def stpage(request,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    if mobileBrowser(request):
        return render_to_response('quizs/m_stpage.html', context_instance=RequestContext(request,{'user' : user, 'course' : course}))
    else:    
        return render_to_response('quizs/stpage.html', context_instance=RequestContext(request,{'user' : user, 'course' : course}))

def stsubpage(request,user_id,course_id):
    user=request.user
    sub=User.objects.get(pk=user_id)
    course=Course.objects.get(pk=course_id)
    return render_to_response('quizs/stsubpage.html', context_instance=RequestContext(request,{'user' : user, 'course' : course, 'sub' : sub}))

def prepare(request,lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    quizes=Quiz.objects.filter(lecture=lecture)
    return render_to_response('quizs/upcoming.html', context_instance=RequestContext(request,{'user' : user,'lecture': lecture, 'course':lecture.course, 'quizes': quizes}))
    
def listquizes(request,course_id,user_id):
    user=request.user
    sub=User.objects.get(pk=user_id)
    course=Course.objects.get(pk=course_id)
    lectures=Lecture.objects.filter(course=course)
    quizs=[]
    for lecture in lectures:
       quizes=Quiz.objects.filter(lecture=lecture)
       for quiz in quizes:
           
           quizs.append(quiz)
    return render_to_response('quizs/list.html', context_instance=RequestContext(request,{'quizes' : quizs,'user' : user, 'sub' : sub}))

def substats(request,user_id,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    sub=User.objects.get(pk=user_id)
    grades=Grade.objects.filter(user=sub)
    RA=0
    WA=0
    for grade in grades:
	       if grade.quiz.lecture.course==course:
                if grade.choice.isRight:
		          RA=RA+1
               	else:
		          WA=WA+1

    return render_to_response('quizs/substats.html', context_instance=RequestContext(request,{'sub' : sub, 'RA' : RA,'user' : user, 'WA' : WA, "course" : course}))


def lectureDetails(request,lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    filename= lecture.lectureFile.name[21:]
    quizes=Quiz.objects.filter(lecture=lecture)
    if mobileBrowser(request):
      return render_to_response('quizs/m_lecture.html', context_instance=RequestContext(request,{'user' : user, 'lecture' : lecture}))
    else:
      return render_to_response('quizs/lecture.html', context_instance=RequestContext(request,{'quizes' : quizes,'user' : user, 'lecture' : lecture, 'fname' : filename}))


def getQuizzes(request, lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    quizes=Quiz.objects.filter(lecture=lecture)
    return render_to_response('quizs/m_quizzes.html', context_instance=RequestContext(request,{'quizes' : quizes,'user' : user, 'lecture' : lecture}))

def getQuizzes1(request, lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    quizes=Quiz.objects.filter(lecture=lecture)
    return render_to_response('quizs/pquizzes.html', context_instance=RequestContext(request,{'quizes' : quizes,'user' : user, 'lecture' : lecture, 'course': lecture.course}))

def getQuizzes2(request, lecture_id, user_id):
    user=request.user
    sub=User.objects.get(pk=user_id)
    lecture=Lecture.objects.get(pk=lecture_id)
    quizes=Quiz.objects.filter(lecture=lecture)
    return render_to_response('quizs/psubquizzes.html', context_instance=RequestContext(request,{'quizes' : quizes,'user' : user,'sub': sub , 'lecture' : lecture, 'course': lecture.course}))

def confirm(request, answer_id):
    user=request.user
    choice=Answer.objects.get(pk=answer_id)
    return render_to_response('quizs/m_confirm.html', context_instance=RequestContext(request,{'choice' : choice ,'user' : user}))


def submitAnswer(request, choice_id):
    user=request.user
    choice=Answer.objects.get(pk=choice_id)
    if choice.quiz.isEnded:
        return render_to_response('quizs/m_late.html', context_instance=RequestContext(request,{'quiz':choice.quiz,'user' : user}))
    else:
        if choice.isRight:
            gr=Grade.objects.create(grade=choice.quiz.bonusPoints,quiz=choice.quiz, choice=choice, user=user)
            gr.save()
        else:
            gr=Grade.objects.create(grade=0,quiz=choice.quiz, choice=choice, user=user)
            gr.save()
        url='/courses/'+str(choice.quiz.lecture.course.id)
        return HttpResponseRedirect(url)



def startLecture(request, lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    lecture.isStarted=True
    lecture.save()
    url="/quiz/lecture/"+str(lecture_id)        
    return HttpResponseRedirect(url)    



def endLecture(request, lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    lecture.isEnded=True
    lecture.save()
    url='/courses/mycourse/'+str(lecture.course.id)
    return HttpResponseRedirect(url)

def subscribers(request,course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    return render_to_response('quizs/subscribers.html', context_instance=RequestContext(request,{'user' : user, 'course' : course}))

def endQuiz1(request, quiz_id):
    user=request.user
    quiz=Quiz.objects.get(pk=quiz_id)
    quiz.isEnded=True
    quiz.save()
    choices=quiz.answer_set.all()
    Nsub=len(Grade.objects.filter(quiz=quiz))
    
    ListofStats=[]
    for choice in choices:
        grades=Grade.objects.filter(choice=choice)
        n=len(grades)
        list=[]
        list.append(choice.body)
        
        if choice.isRight:
            list.append('(The right Answer)')
            right=choice.body
        list.append(': ')    
        list.append(n)
        ListofStats.append(list)
    
    
    return render_to_response('quizs/endquiz1.html', context_instance=RequestContext(request,{'grades' : grades,'user' : user, 'quiz' : quiz,  'nsub' : Nsub, 'stats' : ListofStats, 'course' : quiz.lecture.course, 'right': right}))



def endQuiz(request, quiz_id):
    user=request.user
    quiz=Quiz.objects.get(pk=quiz_id)
    quiz.isEnded=True
    quiz.save()
    choices=quiz.answer_set.all()
    Nsub=len(Grade.objects.filter(quiz=quiz))
    ListofStats=[]
    for choice in choices:
        grades=Grade.objects.filter(choice=choice)
        n=len(grades)
        list=[]
        list.append(choice.body)
        
        if choice.isRight:
            list.append('(The right Answer)')
        list.append(': ')    
        list.append(n)
        ListofStats.append(list)
    
    
    return render_to_response('quizs/endquiz.html', context_instance=RequestContext(request,{'grades' : grades,'user' : user, 'quiz' : quiz,  'nsub' : Nsub, 'stats' : ListofStats}))

def takeQuiz(request, course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    lectures=Lecture.objects.filter(course=course)
    for lecture in lectures:
        if lecture.isStarted:
            if not lecture.isEnded:
                quizes=Quiz.objects.filter(lecture=lecture)
                for quiz in quizes:
                    if quiz.isStarted:
                        if not quiz.isEnded:
                            grade=Grade.objects.filter(quiz=quiz,user=user)
                            if len(grade)==0:
                                choices=Answer.objects.filter(quiz=quiz)
                                return render_to_response('quizs/m_take.html', context_instance=RequestContext(request,{'user' : user, 'quiz' : quiz ,'choices' : choices}))
                            else:
                                return render_to_response('quizs/m_prev.html', context_instance=RequestContext(request,{'user' : user, 'quiz' : quiz }))
                                
                 
    return render_to_response('quizs/m_noq.html', context_instance=RequestContext(request,{'user' : user,'course':course}))

def writeMessage(request, course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    lectures=Lecture.objects.filter(course=course)
    for lecture in lectures:
        if lecture.isStarted:
            if not lecture.isEnded:
                                return render_to_response('quizs/m_tweet.html', context_instance=RequestContext(request,{'user' : user, 'lecture' : lecture}))
           
                 
    return render_to_response('quizs/m_nol.html', context_instance=RequestContext(request,{'user' : user,'course' : course}))
def listMessages(request,lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    msgs1=Message.objects.filter(lecture=lecture)
    msgs=reversed(msgs1)
    length=len(msgs1)
    z=0
    return render_to_response('quizs/m_msgs.html', context_instance=RequestContext(request,{'z':z, 'user' : user, 'lecture' : lecture,'msgs' : msgs, 'len' : length}))    

def showMessage(request,message_id):
    user=request.user
    message=Message.objects.get(pk=message_id)
    return render_to_response('quizs/m_msg.html', context_instance=RequestContext(request,{'user' : user, 'msg' : message}))    

def showMessage1(request,message_id):
    user=request.user
    message=Message.objects.get(pk=message_id)
    return render_to_response('quizs/m_msg1.html', context_instance=RequestContext(request,{'user' : user, 'msg' : message}))    

def fetch(request, lecture_id, length):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    msgs=Message.objects.filter(lecture=lecture)
    l1= len(msgs)
    l2= length
    return render_to_response('quizs/fetcher.html', context_instance=RequestContext(request,{'user' : user,'lecture':lecture,'l1' : l1,'l2' : l2}))

#    url='/messages/list/'+str(lecture_id)
 #   return HttpResponseRedirect(url)

def submitMessage(request,lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    
    
    tmptitle=request.POST['title']
    
    tmpcontent=request.POST['content']
    
    tmp=Message.objects.create(title=tmptitle, content=tmpcontent, sender=user, lecture=lecture)
    print tmp.title
    tmp.save()
    URL='/courses/'+str(lecture.course.id)
    return HttpResponseRedirect(URL)

def startQuiz(request, quiz_id):
    user=request.user
    quiz=Quiz.objects.get(pk=quiz_id)
    if quiz.isStarted:
        url='/quiz/end/'+str(quiz_id)
        return HttpResponseRedirect(url)
    quiz.isStarted=True
    quiz.save()
           
    return render_to_response('quizs/quiz.html', context_instance=RequestContext(request,{'user' : user, 'quiz' : quiz}))

  
def createLecture(request, course_id):
    user=request.user
    course=Course.objects.get(pk=course_id)
    if request.method=='POST':
        tmptitle=request.POST['title']
        tmpfile=request.FILES['file']
        
        l=Lecture.objects.create(title=tmptitle,isEnded=False,course=course,isStarted=False,lectureFile=tmpfile)
        l.save()
        url='/courses/mycourse/'+str(course_id)
        return HttpResponseRedirect(url)
    else:
           if mobileBrowser(request):
                  return render_to_response('quizs/m_create_lecture.html', context_instance=RequestContext(request,{'user' : user, 'cid' : course_id}))
           else:
                  return render_to_response('quizs/create_lecture.html', context_instance=RequestContext(request,{'user' : user,'course' : course , 'cid' : course_id}))
      
    
def createQuiz(request, lecture_id):
    user=request.user
    lecture=Lecture.objects.get(pk=lecture_id)
    if request.method== 'POST':
        Tmpduration= request.POST['duration']
        print Tmpduration
        i=1
        tmpgrade=request.POST['qgrade']
        tmptitle=request.POST['qbody']
        tmpquiz=Quiz.objects.create(bonusPoints=tmpgrade,title=tmptitle,isEnded=False,duration=Tmpduration,lecture=lecture, isStarted=False)
        tmpquiz.save()
        tmpc1=request.POST['choice1']
        if not tmpc1 =="":
            if request.POST.get('chk1'):
                ans1=Answer.objects.create(body=tmpc1,isRight=True,quiz=tmpquiz)
                ans1.save()
            else:
                ans1=Answer.objects.create(body=tmpc1, isRight=False, quiz=tmpquiz)
                ans1.save()
        tmpc2=request.POST['choice2']
        if not tmpc2 =="":
            if request.POST.get('chk2'):
                ans2=Answer.objects.create(body=tmpc2,isRight=True,quiz=tmpquiz)
                ans2.save()
            else:
                ans2=Answer.objects.create(body=tmpc2, isRight=False, quiz=tmpquiz)
                ans2.save()
        tmpc3=request.POST['choice3']
        if not tmpc3 =="":
            if request.POST.get('chk3'):
                ans3=Answer.objects.create(body=tmpc3,isRight=True,quiz=tmpquiz)
                ans3.save()
            else:
                ans3=Answer.objects.create(body=tmpc3, isRight=False, quiz=tmpquiz)
                ans3.save()
        tmpc4=request.POST['choice4']
        if not tmpc4 =="":
            if request.POST.get('chk4'):
                ans4=Answer.objects.create(body=tmpc4,isRight=True,quiz=tmpquiz)
                ans4.save()
            else:
                ans4=Answer.objects.create(body=tmpc4, isRight=False, quiz=tmpquiz)
                ans4.save()
        
        
        url="/courses/mycourse/"+str(lecture.course.id)        
        return HttpResponseRedirect(url)

            
    else:
	       if mobileBrowser(request):
        	      return render_to_response('quizs/m_create_quiz.html', context_instance=RequestContext(request,{'user' : user, 'lid' : lecture_id}))
	       else:
        	      return render_to_response('quizs/create_quiz.html', context_instance=RequestContext(request,{'user' : user, 'lid' : lecture_id}))

